package com.fpj.sat.vehicle_administrator.util;

import java.awt.BorderLayout;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class ProgressDialog extends JDialog{
	
	private static final long serialVersionUID = 2618386704879341654L;
	private int start;
	private int end;
	private boolean terminate;
	private boolean ok;
	private String errorMessage;
	private JDialog dialog;
	private JFrame frame;

	public ProgressDialog(JDialog dialog, int start, int end) {
		super(dialog, "Progress Dialog", true);
		this.start = start;
		this.end = end;
		this.dialog = dialog;
		inicializaDialog();
	}
	
	public ProgressDialog(JFrame frame, int start, int end) {
		super(frame, "Progress Dialog", true);
		this.start = start;
		this.end = end;
		this.frame = frame;
		inicializaDialog();
	}
	
	private void inicializaDialog(){
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
	    setSize(300, 70);
	    if(dialog != null)
	    	setLocationRelativeTo(dialog);
	    else
	    	setLocationRelativeTo(frame);
	    
	}

	public void iniciaProgress() {
	    final JProgressBar pbProcesando = new JProgressBar(start, end);
	    pbProcesando.setStringPainted(true);
	    add(BorderLayout.NORTH, pbProcesando);

	    Thread t = new Thread(new Runnable() {
	      public void run() {
	    	  int i = start;
	  	    while(true) {
	  	    	if(i % 200 == 0 && i < end){
	  	    		pbProcesando.setValue(i);
	  	    		pbProcesando.setString((int)Math.round((i*0.1))+"%");
	  	    	}
	  	      try {
	  	    	if(terminate){
	  	    		pbProcesando.setValue(end);
	  	    		pbProcesando.setString((int)Math.round((end*0.1))+"%");
		  	    	Thread.sleep(5);
		  	    	  break;
		  	      }
	  	        Thread.sleep(15);
	  	      } catch (InterruptedException e) {
	  	        e.printStackTrace();
	  	      }
	  	      i++;
	  	    }
	  	    setVisible(false);
	      }
	    });
	    t.start();
	    setVisible(true);
	}

	public boolean isTerminate() {
		return terminate;
	}

	public void setTerminate(boolean terminate) {
		this.terminate = terminate;
	}

	public boolean isOk() {
		return ok;
	}

	public void setOk(boolean ok) {
		this.ok = ok;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

}
